<template>
    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑任务' : '创建任务'"
      width="80%"
      :before-close="handleClose"
      draggable
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="task-form"
      >
        <!-- 基本信息 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-title">
              <el-icon><InfoFilled /></el-icon>
              基本信息
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :xs="24" :md="12">
              <el-form-item label="任务名称" prop="taskName">
                <el-input
                  v-model="formData.taskName"
                  placeholder="请输入任务名称"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="任务等级" prop="taskLevel">
                <el-select v-model="formData.taskLevel" placeholder="请选择任务等级" style="width: 100%">
                  <el-option label="部门任务" value="部门任务" />
                  <el-option label="项目任务" value="项目任务" />
                  <el-option label="紧急任务" value="紧急任务" />
                  <el-option label="日常任务" value="日常任务" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="岗位需求" prop="positionRequirement">
                <el-select v-model="formData.positionRequirement" placeholder="请选择岗位需求" style="width: 100%">
                  <el-option label="科研助理" value="科研助理" />
                  <el-option label="业务秘书" value="业务秘书" />
                  <el-option label="技术开发" value="技术开发" />
                  <el-option label="项目管理" value="项目管理" />
                  <el-option label="数据分析师" value="数据分析师" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="人数需求" prop="personnelCount">
                <el-input-number
                  v-model="formData.personnelCount"
                  :min="1"
                  :max="10"
                  placeholder="请输入人数需求"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="任务状态" prop="taskStatus">
                <el-select v-model="formData.taskStatus" placeholder="请选择任务状态" style="width: 100%">
                  <el-option label="未承接" value="未承接" />
                  <el-option label="已承接" value="已承接" />
                  <el-option label="承接中" value="承接中" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="发起人" prop="initiator">
                <el-input
                  v-model="formData.initiator"
                  placeholder="请输入发起人"
                  :disabled="isEdit"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
  
        <!-- 时间设置 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-title">
              <el-icon><Clock /></el-icon>
              时间设置
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :xs="24" :md="8">
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker
                  v-model="formData.startDate"
                  type="date"
                  placeholder="选择开始日期"
                  style="width: 100%"
                  :disabled-date="disabledStartDate"
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="8">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="formData.endDate"
                  type="date"
                  placeholder="选择结束日期"
                  style="width: 100%"
                  :disabled-date="disabledEndDate"
                />
              </el-form-item>
            </el-col>
            
            <!-- <el-col :xs="24" :md="8">
              <el-form-item label="截止日期" prop="deadline">
                <el-date-picker
                  v-model="formData.deadline"
                  type="date"
                  placeholder="选择截止日期"
                  style="width: 100%"
                  :disabled-date="disabledDeadlineDate"
                />
              </el-form-item>
            </el-col> -->
          </el-row>
          
          <el-alert
            v-if="dateValidationMessage"
            :title="dateValidationMessage"
            type="warning"
            :closable="false"
            show-icon
          />
        </el-card>
  
        <!-- 任务内容 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-title">
              <el-icon><Edit /></el-icon>
              任务内容
            </div>
          </template>
          
          <el-form-item label="任务描述" prop="taskContent">
            <el-input
              v-model="formData.taskContent"
              type="textarea"
              :rows="6"
              placeholder="请详细描述任务内容、要求、目标等..."
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
          
          <!-- 富文本编辑器选项 -->
          <div class="content-tools">
            <el-button-group>
              <el-button size="small" @click="insertTemplate('目标')">
                <!-- <el-icon><Target /></el-icon> -->
                插入目标模板
              </el-button>
              <el-button size="small" @click="insertTemplate('要求')">
                <el-icon><List /></el-icon>
                插入要求模板
              </el-button>
              <el-button size="small" @click="insertTemplate('流程')">
                <el-icon><Operation /></el-icon>
                插入流程模板
              </el-button>
            </el-button-group>
          </div>
        </el-card>
  
        <!-- 附件管理 -->
        <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-title">
              <el-icon><Paperclip /></el-icon>
              附件管理
            </div>
          </template>
          
          <div class="attachment-section">
            <el-upload
              ref="uploadRef"
              class="attachment-upload"
              drag
              multiple
              :auto-upload="false"
              :file-list="attachmentList"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :before-upload="beforeUpload"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 .jpg/.png/.pdf/.doc/.docx/.xls/.xlsx 等格式，单个文件不超过10MB
                </div>
              </template>
            </el-upload>
            
            <!-- 附件列表 -->
            <div v-if="attachmentList.length > 0" class="attachment-list">
              <h4>已选择的附件 ({{ attachmentList.length }})</h4>
              <div class="attachment-items">
                <div 
                  v-for="(file, index) in attachmentList" 
                  :key="index"
                  class="attachment-item"
                >
                  <el-icon class="file-icon"><Document /></el-icon>
                  <div class="file-info">
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-size">{{ formatFileSize(file.size || 0) }}</div>
                  </div>
                  <el-button 
                    type="danger" 
                    size="small" 
                    text
                    @click="removeAttachment(index)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
  
        <!-- 高级选项 -->
        <!-- <el-card shadow="never" class="form-section">
          <template #header>
            <div class="section-title">
              <el-icon><Setting /></el-icon>
              高级选项
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :xs="24" :md="12">
              <el-form-item label="优先级">
                <el-rate
                  v-model="formData.priority"
                  :max="5"
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  :texts="['很低', '较低', '普通', '较高', '很高']"
                  show-text
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="是否公开">
                <el-switch
                  v-model="formData.isPublic"
                  active-text="公开"
                  inactive-text="私有"
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="允许报名">
                <el-switch
                  v-model="formData.allowApply"
                  active-text="允许"
                  inactive-text="不允许"
                />
              </el-form-item>
            </el-col>
            
            <el-col :xs="24" :md="12">
              <el-form-item label="自动分配">
                <el-switch
                  v-model="formData.autoAssign"
                  active-text="启用"
                  inactive-text="手动"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="标签">
            <el-select
              v-model="formData.tags"
              multiple
              filterable
              allow-create
              placeholder="选择或创建标签"
              style="width: 100%"
            >
              <el-option label="紧急" value="紧急" />
              <el-option label="重要" value="重要" />
              <el-option label="技术类" value="技术类" />
              <el-option label="文档类" value="文档类" />
              <el-option label="研发类" value="研发类" />
              <el-option label="测试类" value="测试类" />
            </el-select>
          </el-form-item>
        </el-card> -->
      </el-form>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="handleSaveDraft" :loading="saving">保存草稿</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="saving">
            {{ isEdit ? '更新任务' : '创建任务' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { computed, ref, watch, nextTick } from 'vue';
  import { ElMessage, ElMessageBox, type FormInstance, type UploadFile } from 'element-plus';
  import {
    InfoFilled,
    Clock,
    Edit,
    Paperclip,
    Setting,
    // Target,
    List,
    Operation,
    UploadFilled,
    Document
  } from '@element-plus/icons-vue';
  
  interface TaskInfo {
    id?: number;
    initiator: string;
    taskLevel: string;
    taskName: string;
    positionRequirement: string;
    taskContent: string;
    personnelCount: number;
    applicants: string[];
    assignees: string[];
    workHours: {
      startDate: string;
      endDate: string;
    };
    deadline: string;
    taskStatus: string;
    attachments: string[] | null;
    createdAt?: string;
    updatedAt?: string;
  }
  
  interface FormData {
    taskName: string;
    taskLevel: string;
    positionRequirement: string;
    taskContent: string;
    personnelCount: number;
    taskStatus: string;
    initiator: string;
    startDate: string;
    endDate: string;
    deadline: string;
    priority: number;
    isPublic: boolean;
    allowApply: boolean;
    autoAssign: boolean;
    tags: string[];
  }
  
  interface Props {
    visible: boolean;
    task: TaskInfo | null;
    isEdit: boolean;
  }
  
  interface Emits {
    (e: 'update:visible', value: boolean): void;
    (e: 'refresh'): void;
  }
  
  const props = defineProps<Props>();
  const emit = defineEmits<Emits>();
  
  const visible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  });
  
  // 表单相关
  const formRef = ref<FormInstance>();
  const saving = ref(false);
  const attachmentList = ref<UploadFile[]>([]);
  
  // 表单数据
  const formData = ref<FormData>({
    taskName: '',
    taskLevel: '',
    positionRequirement: '',
    taskContent: '',
    personnelCount: 1,
    taskStatus: '未承接',
    initiator: '',
    startDate: '',
    endDate: '',
    deadline: '',
    priority: 3,
    isPublic: true,
    allowApply: true,
    autoAssign: false,
    tags: []
  });
  
  // 表单验证规则
  const formRules = {
    taskName: [
      { required: true, message: '请输入任务名称', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    taskLevel: [
      { required: true, message: '请选择任务等级', trigger: 'change' }
    ],
    positionRequirement: [
      { required: true, message: '请选择岗位需求', trigger: 'change' }
    ],
    taskContent: [
      { required: true, message: '请输入任务内容', trigger: 'blur' },
      { min: 10, max: 1000, message: '长度在 10 到 1000 个字符', trigger: 'blur' }
    ],
    personnelCount: [
      { required: true, message: '请输入人数需求', trigger: 'blur' }
    ],
    taskStatus: [
      { required: true, message: '请选择任务状态', trigger: 'change' }
    ],
    initiator: [
      { required: true, message: '请输入发起人', trigger: 'blur' }
    ],
    startDate: [
      { required: true, message: '请选择开始日期', trigger: 'change' }
    ],
    endDate: [
      { required: true, message: '请选择结束日期', trigger: 'change' }
    ],
    deadline: [
      { required: true, message: '请选择截止日期', trigger: 'change' }
    ]
  };
  
  // 计算属性
  const dateValidationMessage = computed(() => {
    if (!formData.value.startDate || !formData.value.endDate || !formData.value.deadline) {
      return '';
    }
    
    const start = new Date(formData.value.startDate);
    const end = new Date(formData.value.endDate);
    const deadline = new Date(formData.value.deadline);
    
    if (start >= end) {
      return '开始日期应早于结束日期';
    }
    
    if (deadline < end) {
      return '截止日期应不早于结束日期';
    }
    
    return '';
  });
  
  // 监听任务变化，初始化表单数据
  watch(() => props.task, (newTask) => {
    if (newTask && props.isEdit) {
      formData.value = {
        taskName: newTask.taskName,
        taskLevel: newTask.taskLevel,
        positionRequirement: newTask.positionRequirement,
        taskContent: newTask.taskContent,
        personnelCount: newTask.personnelCount,
        taskStatus: newTask.taskStatus,
        initiator: newTask.initiator,
        startDate: newTask.workHours.startDate,
        endDate: newTask.workHours.endDate,
        deadline: newTask.deadline,
        priority: 3,
        isPublic: true,
        allowApply: true,
        autoAssign: false,
        tags: []
      };
      
      // 设置附件
      if (newTask.attachments) {
        attachmentList.value = newTask.attachments.map((name, index) => ({
          name,
          uid: Date.now() + index,
          status: 'success'
        }));
      }
    } else if (!props.isEdit) {
      // 重置表单
    //   resetForm();
    }
  }, { immediate: true });
  
  // 方法
  const handleClose = () => {
    ElMessageBox.confirm(
      '确定要关闭吗？未保存的数据将丢失。',
      '确认关闭',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      resetForm();
      visible.value = false;
    }).catch(() => {
      // 用户取消
    });
  };
  
  const handleSubmit = () => {
    if (!formRef.value) return;
    
    formRef.value.validate((valid) => {
      if (valid) {
        if (dateValidationMessage.value) {
          ElMessage.error(dateValidationMessage.value);
          return;
        }
        
        saveTask(false);
      } else {
        ElMessage.error('请完善表单信息');
      }
    });
  };
  
  const handleSaveDraft = () => {
    saveTask(true);
  };
  
  const saveTask = async (isDraft: boolean) => {
    saving.value = true;
    
    try {
      // 构造保存数据
      const taskData = {
        ...formData.value,
        workHours: {
          startDate: formData.value.startDate,
          endDate: formData.value.endDate
        },
        attachments: attachmentList.value.map(file => file.name),
        applicants: props.task?.applicants || [],
        assignees: props.task?.assignees || [],
        id: props.task?.id
      };
      
      // 模拟保存操作
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 这里应该调用API保存数据
      // if (props.isEdit) {
      //   await updateTask(taskData);
      // } else {
      //   await createTask(taskData);
      // }
      
      ElMessage.success(isDraft ? '草稿保存成功' : (props.isEdit ? '任务更新成功' : '任务创建成功'));
      
      if (!isDraft) {
        emit('refresh');
        visible.value = false;
      }
    } catch (error) {
      ElMessage.error('保存失败');
    } finally {
      saving.value = false;
    }
  };
  
  const resetForm = () => {
    formData.value = {
      taskName: '',
      taskLevel: '',
      positionRequirement: '',
      taskContent: '',
      personnelCount: 1,
      taskStatus: '未承接',
      initiator: '',
      startDate: '',
      endDate: '',
      deadline: '',
      priority: 3,
      isPublic: true,
      allowApply: true,
      autoAssign: false,
      tags: []
    };
    attachmentList.value = [];
    
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  };
  
  // 日期禁用逻辑
  const disabledStartDate = (time: Date) => {
    return time.getTime() < Date.now() - 8.64e7; // 不能选择昨天之前的日期
  };
  
  const disabledEndDate = (time: Date) => {
    if (!formData.value.startDate) return false;
    return time.getTime() <= new Date(formData.value.startDate).getTime();
  };
  
  const disabledDeadlineDate = (time: Date) => {
    if (!formData.value.endDate) return false;
    return time.getTime() < new Date(formData.value.endDate).getTime();
  };
  
  // 内容模板插入
  const insertTemplate = (type: string) => {
    const templates = {
      '目标': '\n\n【任务目标】\n1. \n2. \n3. \n',
      '要求': '\n\n【具体要求】\n• \n• \n• \n',
      '流程': '\n\n【工作流程】\n第一步：\n第二步：\n第三步：\n'
    };
    
    formData.value.taskContent += templates[type as keyof typeof templates] || '';
  };
  
  // 附件处理
  const handleFileChange = (file: UploadFile) => {
    // 文件大小检查
    if (file.size && file.size > 10 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过10MB');
      return false;
    }
    
    // 文件类型检查
    const allowedTypes = [
      'image/jpeg', 'image/png', 'image/gif',
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    ];
    
    if (file.raw && !allowedTypes.includes(file.raw.type)) {
      ElMessage.error('不支持的文件类型');
      return false;
    }
  };
  
  const handleFileRemove = (file: UploadFile) => {
    const index = attachmentList.value.findIndex(item => item.uid === file.uid);
    if (index > -1) {
      attachmentList.value.splice(index, 1);
    }
  };
  
  const beforeUpload = () => {
    return false; // 阻止自动上传
  };
  
  const removeAttachment = (index: number) => {
    attachmentList.value.splice(index, 1);
  };
  
  const formatFileSize = (size: number) => {
    if (size < 1024) return size + ' B';
    if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB';
    return (size / (1024 * 1024)).toFixed(1) + ' MB';
  };
  </script>
  
  <style lang="scss" scoped>
  .task-form {
    .form-section {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 600;
        color: #000;
        
        .el-icon {
          margin-right: 8px;
          color: #409eff;
        }
      }
    }
    
    .content-tools {
      margin-top: 12px;
      
      .el-button-group {
        .el-button {
          font-size: 12px;
        }
      }
    }
    
    .attachment-section {
      .attachment-upload {
        margin-bottom: 20px;
      }
      
      .attachment-list {
        h4 {
          margin: 0 0 12px 0;
          color: #000;
          font-size: 14px;
        }
        
        .attachment-items {
          .attachment-item {
            display: flex;
            align-items: center;
            padding: 12px;
            margin-bottom: 8px;
            background: #f8f9fa;
            border-radius: 6px;
            border-left: 4px solid #409eff;
            
            .file-icon {
              color: #409eff;
              margin-right: 12px;
              font-size: 20px;
            }
            
            .file-info {
              flex: 1;
              
              .file-name {
                font-size: 14px;
                color: #000;
                margin-bottom: 2px;
              }
              
              .file-size {
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  // 响应式样式
  @media (max-width: 768px) {
    .task-form {
      .content-tools {
        .el-button-group {
          display: flex;
          flex-direction: column;
          
          .el-button {
            margin-bottom: 8px;
            border-radius: 4px !important;
          }
        }
      }
    }
  }
  </style>
  
  <style lang="scss">
  .task-form {
    .el-card__body {
      padding: 16px;
    }
    
    .el-upload-dragger {
      border: 2px dashed #dcdfe6;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      
      &:hover {
        border-color: #409eff;
      }
    }
    
    .el-rate {
      .el-rate__text {
        color: #606266;
      }
    }
  }
  </style>